#include "drv_usart.h"

#if (__ARMCC_VERSION >= 6000000)
	//AC6
	__asm (".global __use_no_semihosting\n\t");
	void _sys_exit(int x)
	{
		x = x;
	}
	/* __use_no_semihosting was requested, but _ttywrch was */
	void _ttywrch(int ch)
	{
		ch = ch;
	}
	FILE __stdout;
#else
	//AC5
	#ifdef __CC_ARM
		#pragma import(__use_no_semihosting)
		struct __FILE
		{
			int handle;
		};
		FILE __stdout;
		void _sys_exit(int x)
		{
			x = x;
		}
		/* __use_no_semihosting was requested, but _ttywrch was */
		void _ttywrch(int ch)
		{
			ch = ch;
		}
	#endif
#endif

#if defined (__GNUC__) && !defined (__clang__)
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif

/**
  * @brief  retargets the c library printf function to the usart.
  * @param  none
  * @retval none
  */
PUTCHAR_PROTOTYPE
{
	while(usart_flag_get(PRINT_UART, USART_TDBE_FLAG) == RESET);
	usart_data_transmit(PRINT_UART, ch);
	return ch;
}


uint8_t usart1_tx_buf[USART1_SEND_LEN];
uint8_t usart1_rx_buf[USART1_REC_LEN];     //接收缓冲,最大USART_REC_LEN个字节.
//接收状态
//bit15，	接收完成标志
//bit14，	接收到0x0d
//bit13~0，	接收到的有效字节数目
uint16_t usart1_rx_sta=0;       //接收状态标记
#include "led.h"

u8 res = 0;
void USART1_IRQHandler(void)
{
	if(usart_flag_get(PRINT_UART, USART_RDBF_FLAG) != RESET)
	{
		res = usart_data_receive(PRINT_UART);
		if((usart1_rx_sta & 0x8000) == 0)
		{
			if(usart1_rx_sta & 0x4000)
			{
				if(res!=0x0a)usart1_rx_sta = 0;
				else usart1_rx_sta |= 0x8000;
			}
			else
			{
				if(res==0x0d)
					usart1_rx_sta |= 0x4000;
				else
				{
					usart1_rx_buf[usart1_rx_sta&0X3FFF] = res ;
					usart1_rx_sta++;
					if(usart1_rx_sta > (USART1_REC_LEN-1))
						usart1_rx_sta=0;
				}
			}
		}
		res = 0;
	}
}

void usart1_send_byte(uint8_t byte)
{
	while(usart_flag_get(PRINT_UART, USART_TDBE_FLAG) == RESET);
	usart_data_transmit(PRINT_UART, byte);
}

void usart1_send_buffer(uint8_t *Buffer, uint32_t Length)
{
	while(Length != 0)
	{
		usart1_send_byte(*Buffer);
		Buffer++;
		Length--;
	}
}

void usart1_send_string(char *str)
{
	while (*str!='\0')
	{
		usart1_send_byte(*str++);
	}
}
